<template>
	<!-- 效期 -->
	<div class="LocationCatalog">
		<!-- main -->
		<div class="main">
			<!-- right -->
			<div class="main-right">
				<!-- tit -->
				<div class="main-icon">
					<div class="main-icon-a">
						<i class="el-icon-xy" style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;background-color: #409EFF;color: #fff;"></i>
						<span style="font-weight:300;margin-left: 12px;">效期统计【西药】</span>
					</div>
					<!-- btn1 -->
					<div class="main-icon-c">
						<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">库房名称：</span>
						<el-select v-model="searchValue" filterable placeholder="" size="mini">
						    <el-option
						      v-for="item in optionks"
						      :key="item.id"
						      :label="item.title"
						      :value="item.id">
						    </el-option>
						</el-select>
					</div>
					<!-- btn2 -->
					<div class="main-icon-c">
						<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 88px;">到期范围：</span>
						<el-input v-model="daysValue" placeholder="" size="mini" style="width: 68px;" 
						  @keyup.native="validateDaysValue"></el-input>
						<span style="font-size: 12px;color: #606266;font-weight: bold;margin-left: 12px;">天内</span>
					</div>
					<!-- btn3 -->
					<div class="main-icon-c">
						<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" 
						  :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
					</div>
				</div>
				<!-- tabs选项卡 -->
				<el-tabs v-model="activeName" type="card" @tab-click="handleClick">
				    <el-tab-pane label="期间统计" name="1">
						<!-- 表格容器 -->
						<div class="table-container">
							<el-table 
							  :data="tableData" 
							  border 
							  @row-dblclick="handledbRow" 
							  element-loading-text="数据加载中..." 
							  v-loading="loading" 
							  element-loading-spinner="el-icon-refresh"
							  highlight-current-row 
							  @current-change="handleCurrentTableChange"
							  style="width: 100%"
							>
								<el-table-column label="系统序号" prop="id" width="88"></el-table-column>
								<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
								<el-table-column fixed="left" label="行号" type="index" width="50"></el-table-column>
							</el-table>
						</div>
						<!-- 固定在底部的分页 -->
						<div class="pagination-footer">
							<el-pagination
							  @size-change="handleSizeChange"
							  @current-change="handleCurrentChange"
							  :current-page="pageNum"
							  :page-sizes="[8, 10, 20]"
							  :page-size="pageSize"
							  :total="totalSize"
							  layout="total, sizes, prev, pager, next, jumper"
							  background
							>
							</el-pagination>
						</div>
					</el-tab-pane>
				    <el-tab-pane label="过期统计" name="2">
						<!-- 表格容器 -->
						<div class="table-container">
							<el-table 
							  :data="tableData" 
							  border 
							  @row-dblclick="handledbRow"
							  element-loading-text="数据加载中..." 
							  v-loading="loading" 
							  element-loading-spinner="el-icon-refresh"
							  highlight-current-row 
							  @current-change="handleCurrentTableChange"
							  style="width: 100%"
							>
								<el-table-column label="系统序号" prop="id" width="88"></el-table-column>
								<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
								<el-table-column fixed="left" label="行号" type="index" width="50"></el-table-column>
							</el-table>
						</div>
						<!-- 固定在底部的分页 -->
						<div class="pagination-footer">
							<el-pagination
							  @size-change="handleSizeChange"
							  @current-change="handleCurrentChange"
							  :current-page="pageNum"
							  :page-sizes="[8, 10, 20]"
							  :page-size="pageSize"
							  :total="totalSize"
							  layout="total, sizes, prev, pager, next, jumper"
							  background
							>
							</el-pagination>
						</div>
					</el-tab-pane>
				</el-tabs>
			</div>
		</div>
	</div>
</template>

<script>
	// selfs / js
	// import LocationCatalog from '@/external/LocationCatalog.js'
	//  selfs / props
	// import addModel from './traMedici/addDialogVisible.vue'
	// 接口
	import { ExpireWarn }  from "@/api/PSI.js";
	
	export default {
		inject: ['reload'], // 无痕刷新
		components: {
			// addModel
		},
		data() {
			return {
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// str
				toCode:'',
				daysValue:30, // 到期范围筛选
				activeName:'1',
				windowWidth: '', //表格自适应宽度
				searchValue:1,
				CatalogueName:'效期统计',
				DropDownedName:'',
				iconComes:'el-icon-yllb',
				// boolean
				loading:false,
				disabled:true,
				// showChild:false, // 控制子组件挂载
				// number
				pageNum: 1, //当前页currentPage
				pageSize: 8,
				totalSize: 10, //总条数
				pageSizeSave:0,
				// arr
				form: {},
				editform:{},
				res:[],
				NameOptions:[],
				restaurants: [], // 搜索关键字
				optionks:[{id:1,title:'西药库'}],
				// title右侧按钮
				headerBtn:[
					{ title:"查询", type:"primary" },{ title:"刷新", type:"", icon:"el-icon-refresh", loading:false}, { title:"高级", type:"", icon:"", loading:false},
				],
				// tableRows
				tableRows:[
					{ name:"药品名称", prop:"drugName", drugType:"" },
					{ name:"规格描述", prop:"drugSpec"},{ name:"生产厂家", prop:"prodentpName", drugType:"" },
					{ name:"有效日期", prop:"expyDate" },{ name:"倒计天数", prop:"remainDay", drugType:"" },
					{ name:"库存数量", prop:"purcCnt", drugType:"" },{ name:"剂量单位", prop:"untName"},
					{ name:"成本单价", prop:"purcPric", },{ name:"成本金额", prop:"purcAmt"},
					{ name:"销售单价", prop:"salePric", drugType:"" },{ name:"销售金额", prop:"saleAmt", drugType:"" },
					{ name:"生产批号", prop:"manuLotnum", drugType:"" },
				],
				elTree:[
					{ label: '全部', path:'', title:'', icon:'el-icon-news',
						children:[
							{ id:1,label: '中药饮片',path:'',title:'中药饮片',icon:'el-icon-byj'},
							{ id:2,label: '中药颗粒',path:'',title:'中药颗粒',icon:'el-icon-qjtyw'},
						],
					},
				],
				tableData: [
					{ id:'1', code:'X0000001164', genericName: '尼可刹米注射液', drugType:'西药', drugDosage:'注射剂', poisonousType:'普通药',yt:'非液体',lc:'', drugCategory:'神经系统用药', sonKinds:'中枢神经兴奋药',IIIkinds:'', ATC:'否', TATC:'否', OTC:'否', oral:'否', date: '2024-11-26 21：30：22', Opter:'admin', status: '可用', nz: '否',yn:'否',ps:'否',js:'否',zl:'否',rs:'否',priceKinds:'西药费',jk:'否',db:'否',dangerous:'非高危药品',remark:' ' },
					{ id:'2', code:'X0000001165', genericName: '注射用重组人白介素_2（123ALA）', drugType:'西药', jix:'注射剂',yt:'非液体',lc:'', poisonousType:'普通药', drugCategory:'血液系统用药', sonKinds:'升血细胞药',IIIkinds:'升血小板药', ATC:'否', TATC:'否', OTC:'否', oral:'否', date: '2024-11-02 08：28：02', Opter:'杨勇', status: '可用', nz: '否',yn:'否',ps:'否',js:'否',zl:'否',rs:'否',priceKinds:'西药费',jk:'否',db:'否',dangerous:'非高危药品',remark:' ' },
				],
			};
		},
		computed: {
		   
		  },
		mounted() {
			// 数据源
			this.loadData();
			//获取动态盒子宽度，实时赋值给右侧 =i> this.$refs.mainRight.offsetWidth;
			this.$nextTick(() => {
				this.updateTableHeight();
				window.addEventListener('resize', this.updateTableHeight);
			});
		},
		beforeDestroy() {
			window.removeEventListener('resize', this.updateTableHeight);
		},
		methods: {
			/*
				数据源
			*/
			// 验证daysValue是否为数字
			validateDaysValue() {
				// 移除非数字字符
				this.daysValue = this.daysValue.replace(/[^\d]/g, '');
			},
			
			// 查询数据
			async loadData(){
				// 验证daysValue是否为有效数字
				if(!this.daysValue || isNaN(this.daysValue)) {
					this.$message.warning('请输入有效的天数');
					return;
				}
				
				try {
					this.loading = true;
					let res = await ExpireWarn({
						day: parseInt(this.daysValue) || 30, // 确保是数字，默认30
						type: this.activeName
					});
					
					if(res.code === 200){
						this.$message.success(res.message || '查询成功');
						this.tableData = res.data;
					} else {
						this.$message.error(res.message || '获取数据失败');
					}
				} catch (error) {
					console.error('获取数据出错:', error);
					this.$message.error('获取数据时出错');
				} finally {
					this.loading = false;
				}
			},
			// props
			querySearch(queryString, cb) {
			    
			},
			
			// 更新表格高度
			updateTableHeight() {
				this.$nextTick(() => {
					// 计算可用高度
					const headerHeight = document.querySelector('.main-icon')?.offsetHeight || 80;
					const tabsHeight = document.querySelector('.el-tabs__header')?.offsetHeight || 40;
					const paginationHeight = 60; // 分页高度估计值
					const windowHeight = window.innerHeight;
					
					// 减去所有固定高度元素的高度
					const availableHeight = windowHeight - headerHeight - tabsHeight - paginationHeight - 20; // 20为其他边距
					
					// 设置表格容器高度
					const containers = document.querySelectorAll('.table-container');
					containers.forEach(container => {
						container.style.height = `${Math.max(availableHeight, 188)}px`; // 最小高度188px
						container.style.overflow = 'hidden';
					});
					
					// 设置表格内部滚动
					const tables = document.querySelectorAll('.el-table__body-wrapper');
					tables.forEach(table => {
						table.style.maxHeight = `${availableHeight - 40}px`; // 减去表头高度
						table.style.overflowY = 'auto';
					});
				});
			},
			createFilter(queryString) {
				return (restaurant) => {
				  return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
				};
			},
			handleClick(tab, event) {
				this.loadData();
			},
			handleSelect(item) {
				console.log(item);
			},
			handleIconClick(ev) {
				console.log(ev);
			},
			/*
				about tree
			*/
			async handleNodeClick(data){
				console.log(data);
			},
			// 选择值
			handClickName(val){
				console.log(val);
			},
			//新增保存
			addNewDiction(){
				
			},
			
			// edit
			async editFormValue(row){
				if(row){
					this.loading = true;
					setTimeout(()=>{
						// 使用点语法
						// res.data.watch = true;
						let param = {
							id:row.id,
							label:'编辑',
							isShow:true,
							system:true,
						}
						this.loading = false;
						this.$refs.addModel.openAddModel(param);
					},888)
				} else { 
					this.$message({ type: "info", message: "未知异常，请稍后重试！"});
				}
			},
			handleDelete(rowId){
				console.log(rowId);
				this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(async() => {
					let ress = await deleteTP({
						id: rowId
					})
					if(ress.code === 200){
						this.$message({type:'success',message:'已删除'});
						this.loadData();
					}else{
						this.$message.error(ress.message)
					}
				}).catch(() => {
				  this.$message({
					type: 'info',
					message: '已取消删除'
				  });          
				});
			},
			
			// 编辑保存
			saveEditData(){
				
			},
			
			/*
				选择框
			*/

			/*
				about input
			*/

			/*
				about table
			*/
		    // col 里面包含了表头字段和名称，list 是表格数据
		    columnWidth(col, list) {
		         let prop = col.prop,lab = col.lab;
		         let width = 40; // 设定一个最小值
		         let maxlenStr = ""; // 最长字符串
		         for (let info of list) {
		           if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		         }
		         width = Math.max(width, len(lab), len(maxlenStr));
		         // 表格自带的内边距(20px) 自调
		         return width + 12; // 这里加了 12px
		         function len(str) {
		           // 实际分配长度可根据需要自行调整
		           let length = 0;
		           for (const char of str + "") {
		             // 英文小写字符 8px
		             if ("a" <= char && char <= "z") length += 18;
		             // 英文大写字符 12px
		             else if ("A" <= char && char <= "Z") length += 18;
					 // 数字
					 else if (Number.isFinite(Number(char))) length += 12;
		             // 中文字符 16px
		             else if (char >= "\u4e00" && char <= "\u9fa5") length += 22;
		             // 其他 8px
		             else length += 12;
		           }
		           return length;
		         }
		    },

			// 按钮点击事件
			handClick(i) {
				switch (i) {
					case 0: // 查询按钮
						// 验证daysValue是否为有效数字
						if(!this.daysValue || isNaN(this.daysValue)) {
							this.$message.warning('请输入有效的天数');
							return;
						}
						this.loadData();
						break;
						
					case 1: // 刷新按钮
						this.loading = true;
						setTimeout(() => {
							this.reload();
							this.$message.success('已刷新');
							this.loading = false;
						}, 500);
						break;
						
					case 2: // 高级按钮
						this.$message.info("暂不支持,请联系工作人员!");
						break;
				}
			},
			// 表格单选
			handleCurrentTableChange(val){
				console.log(val);
				this.currentTable = val
			},
			// db events 双击表格行
			handledbRow(row, column, event){
				if(row){
					this.loading = true;
					setTimeout(()=>{
						console.log(row,'双击过后查看');
						// 使用点语法
						// res.data.watch = true;
						let param = {
							id:row.id,
							label:'查看',
							isShow:false,
							system:true,
						}
						this.loading = false;
						this.$refs.addModel.openAddModel(param);
					},888)
				} else { 
					this.$message({ type: "info", message: "未知异常，请稍后重试！"});
				}
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					this.formdisabled = true;
					location.reload();
					done();
				  })
				  .catch(_ => {
					this.formdisabled = this.formdisabled;
				  });
			},
			handleCommand(command) {
			  // 这里的 command 就是你点击的菜单项的 command 属性值
			  // console.log(command);
			  // 根据 command 值执行相应的逻辑
			  switch (command) {
				case 'a':
				  // 处理a的逻辑
				  console.log('执行A逻辑');
				  this.DropDownedName = '可用'
				  break;
				case 'b':
				  // 处理b的逻辑
				  console.log('执行B逻辑');
				  this.DropDownedName = '禁用'
				  break;
				case 'c':
				  // 处理b的逻辑
				  this.DropDownedName = '全部'
				  break;
				// ... 其他 case
			  }
			},
			// 拦截

			//分页
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageNum = val;
				this.loadData();
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
				this.loadData();
			},
			// 实时宽度
			updateWindowWidth() {
			    this.windowWidth = window.innerWidth - 228;
			},
		}
	}
</script>

<style lang="less" scoped>
	.LocationCatalog {
		height: 100vh;
		width: 100%;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		
		.main {
			flex: 1;
			display: flex;
			flex-direction: column;
			overflow: hidden;
			padding: 4px;
			
			.main-right {
				flex: 1;
				display: flex;
				flex-direction: column;
				overflow: hidden;
				
				.main-icon {
					display: flex;
					align-items: center;
					padding: 6px;
					line-height: 40px;
					flex-wrap: wrap;
					gap: 12px;
					flex-shrink: 0; // 防止高度变化
				}
				
				.el-tabs {
					flex: 1;
					display: flex;
					flex-direction: column;
					overflow: hidden;
					
					::v-deep .el-tabs__content {
						flex: 1;
						display: flex;
						flex-direction: column;
						overflow: hidden;
						
						.el-tab-pane {
							flex: 1;
							display: flex;
							flex-direction: column;
							overflow: hidden;
						}
					}
				}
				
				.table-container {
					flex: 1;
					display: flex;
					flex-direction: column;
					overflow: hidden;
					
					.el-table {
						flex: 1;
						display: flex;
						flex-direction: column;
						overflow: hidden;
						
						::v-deep .el-table__header-wrapper {
							flex-shrink: 0;
						}
						
						::v-deep .el-table__body-wrapper {
							flex: 1;
							overflow-y: auto;
						}
					}
				}
				
				.pagination-footer {
					padding: 12px;
					background-color: #fff;
					border-top: 1px solid #ebeef5;
					position: sticky;
					bottom: 0;
					z-index: 10;
					flex-shrink: 0; // 防止高度变化
				}
			}
		}
		
		/* 自定义高亮颜色 */
		::v-deep .el-table__body tr.current-row > td {
			background-color: #00557f !important;
			color: #f9f9f9;
		}
		
		::v-deep .el-table {
			.cell {
				font-size: 12px;
				text-overflow: ellipsis;
				white-space: nowrap;
				overflow: hidden;
			}
			
			th {
				background-color: #f1f1f1;
				border: none;
				color: #2d2d2d;
			}
		}
	}
</style>